package com.hrg.seer.sdk.rbk;

import cn.hutool.json.JSONUtil;
import com.hrg.rds.biz.config.RdsConfiguration;

import com.hrg.rds.biz.robot.domain.AgvVo;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
class RbkInboundHandler extends SimpleChannelInboundHandler<RbkFrame> {
    private RbkClient rbkClient;
    private RbkPortClient rbkPortClient;

    private AgvVo agvVo;

    public RbkInboundHandler(RbkPortClient rbkPortClient) {
        this.rbkPortClient = rbkPortClient;
        this.rbkClient = RdsConfiguration.AgvIpClientMap.get(this.rbkPortClient.getHost());
        this.agvVo = RdsConfiguration.AgvIpMap.get(this.rbkPortClient.getHost());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RbkFrame msg) throws Exception {
        try {
            if (msg.getApiNo() == 19301) {
                rbkPortClient.onPushedMessage(msg.getBodyStr());
            } else {
                log.debug("收到消息，ip = {}, port = {}, msg = {}", this.rbkPortClient.getHost(),this.rbkPortClient.getPort(), JSONUtil.toJsonStr(msg));
                rbkPortClient.onMessage(ctx, msg);
            }
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        try {
            ctx.close();
        } catch (Exception e) {
            //
        }
        rbkPortClient.onError(cause);
    }
    
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("连接激活 ip = {}, port = {}", this.rbkPortClient.getHost(), this.rbkPortClient.getPort());
        this.rbkClient.getConnectOkCnt().incrementAndGet();
        this.agvVo.onConnectActive(rbkClient.isIfConnectOk());
        super.channelActive(ctx);
    }
    
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Integer port = this.rbkPortClient.getPort();
        log.info("连接断开 ip = {}, port = {}", this.rbkPortClient.getHost(), port);
        this.rbkClient.getConnectOkCnt().decrementAndGet();
        this.agvVo.onConnectInactive(port);
        this.rbkPortClient.getNettyClient();
        super.channelInactive(ctx);
    }

}
